<template>
    <div>
        <div class="container">
            <el-button type="warning" :icon="CirclePlusFilled" style="margin-bottom: 10px" @click="visible = true">新增</el-button>
        <el-table
          :data="tableData"
          :preserve-expanded-content="true"
          style="height: calc(100vh - 300px);"
          row-key="id"
        :expand-row-keys="expandedRowKeys"
          @expand-change="handleExpandChange"
        >
          <el-table-column type="expand">
            <template #default="{ row}">
                <el-table :data="row.flows" class="no-header-bg" > 

                  <el-table-column label="录入时间" prop="createTime" />    
                  <el-table-column label="收入金额(元)" prop="inAmount" />
                  <el-table-column label="支出金额(元)" prop="outAmount" />
                  <el-table-column label="本次总额(元)" :formatter="(row) => row.inAmount - row.outAmount" />
                    <el-table-column label="操作" width="200px">
                        <template #default="{ row: flowRow }">
                                <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(flowRow)">
                                    编辑
                                </el-button>
                                <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(flowRow)">
                                    删除
                                </el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </template>
          </el-table-column>
          <el-table-column label="公司名称" prop="companyName" />
          <el-table-column label="日期" prop="flowDate" />
          <el-table-column label="余额(元)" prop="balance" />

          <el-table-column label="最近录入时间" prop="updateTime" />

        </el-table>
          <el-pagination v-if="hasPagination" :page-size="page.size" :background="false"
                         :page-sizes="[10, 20, 50, 100]"  @size-change="handleSizeChange"
                         layout="sizes,prev, pager, next" :total="page.total" @current-change="handleCurrentChange" style="margin-top: 10px" />
        </div>
        <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" />
        </el-dialog>
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="finance-management">

import { ref, reactive,onMounted,watch,nextTick } from 'vue';


import { ElMessage } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { fetchFinanceAccountData,saveFinanceAccountFlowData,delFinanceAccountFlowById,fetchCompanyData } from '@/api';
import TableDetail from '@/components/table-detail.vue';
import { Finance } from '@/types/dto';
import { FormOption, FormOptionList } from '@/types/form-option';
import { Delete, Edit, View, Refresh } from '@element-plus/icons-vue';

const hasPagination = ref(true);
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const expandedRowKeys = ref([]); // 用于控制展开行的数组


// 处理展开事件，更新 flowsArray 和 row.balance
const handleExpandChange = (row, expandedRows) => {
    expandedRowKeys.value = expandedRows.map(r => r.id); // 更新展开行的 keys


};

onMounted(async () => {
    const res = await fetchCompanyData();
    const opts = res.data.map(item => ({

        label: item.companyName,
        value: item.companyName
    }));
    const companyItem = options.value.list.find(item => item.prop === 'companyName');
    if (companyItem) {
        companyItem.opts = opts;
    }
    
});

// 监听 isEdit 的变化，并更新 options 中的 disabled 属性
watch(isEdit, (newVal) => {
    options.value.list.forEach(item => {
        if (item.prop === 'companyName' || item.prop === 'flowDate') {
            item.disabled = newVal;
        }

    });
});


const handleCurrentChange = (val: number) => {
    page.index = val;
    page.currentPage = val;
    getData();
};

const handleSizeChange = (val: number) => {
    page.size = val;
    page.index = 1;
    page.currentPage = 1;
    getData();
};

const page = reactive({
    total: 0,
    index: 1,
    size: 50,
    hasPagination: true,
    layout: 'prev, pager, next,total',
    currentPage: 1,
    pageCount: 1
})
const tableData = ref<Finance[]>();
const getData = async () => {
    const res = await fetchFinanceAccountData(page.index, page.size);
    tableData.value = res.data.content;
    page.index = res.data.number + 1;
    page.total = res.data.totalElements;
    page.size = res.data.size;
    page.pageCount = res.data.totalPages;
};

getData();


// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '序号', prop: 'id', required: false, disabled: true},
        { type: 'select', prop: 'companyName', label: '公司名称' , required: true, disabled: isEdit.value  },
        { type: 'date',format: 'YYYY-MM-DD', prop: 'flowDate', label: '贷款到期日期' , disabled: isEdit.value  },
        { type: 'number', prop: 'inAmount', label: '收入金额(元)', required: true },
        { type: 'number', prop: 'outAmount', label: '支出金额(元)', required: true },

    ]
})

const handleEdit = (row) => {
    isEdit.value = true;
    visible.value = true;
    rowData.value = { ...row };
    
};
const updateData = async (data) => {
    await saveFinanceAccountFlowData(data);
    if (!isEdit.value) {
        ElMessage.success('新增成功');
    } else {
        ElMessage.success('编辑成功');
    }
    closeDialog();
    getData();
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});


// 删除相关
const handleDelete = async (row) => {
    await delFinanceAccountFlowById(row.id);
    await getData();
}
</script>

<style>

.container {
    min-height: calc(100vh - 150px) !important; 
    box-sizing: border-box;
    background: #fff;
    padding: 20px;
    overflow: auto;
}

.el-table.no-header-bg th {
    height: 40px;
    background-color: #fff !important;
    font-weight: normal;
    text-align: center !important;

}
.el-table th.el-table__cell  {
    text-align: center !important;
}

.el-table td.el-table__cell{
    text-align: center !important;
}

</style>